package cn.minsh.lims.eoms.modules.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.minsh.lims.eoms.common.exception.RRException;
import cn.minsh.lims.eoms.common.utils.ObjectToMapUtils;
import cn.minsh.lims.eoms.common.utils.PageUtils;
import cn.minsh.lims.eoms.common.utils.Query;
import cn.minsh.lims.eoms.modules.app.controller.req.*;
import cn.minsh.lims.eoms.modules.app.controller.req.app.AppUserRepairListReq;
import cn.minsh.lims.eoms.modules.app.controller.res.RepairOrderInfoRes;
import cn.minsh.lims.eoms.modules.app.controller.res.app.AppRepairListRes;
import cn.minsh.lims.eoms.modules.app.dao.RepairOrderDao;
import cn.minsh.lims.eoms.modules.app.entity.PicEntity;
import cn.minsh.lims.eoms.modules.app.entity.PlanScopeEntity;
import cn.minsh.lims.eoms.modules.app.entity.RepairOrderEntity;
import cn.minsh.lims.eoms.modules.app.entity.RepairOrderRecordEntity;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.OrderStatusEnum;
import cn.minsh.lims.eoms.modules.app.enums.RepairLeveEnum;
import cn.minsh.lims.eoms.modules.app.message.CompleteRepairOrderMsg;
import cn.minsh.lims.eoms.modules.app.message.RejectOrderMsg;
import cn.minsh.lims.eoms.modules.app.message.RepairOrderMsg;
import cn.minsh.lims.eoms.modules.app.service.*;
import cn.minsh.lims.eoms.modules.app.utils.*;
import cn.minsh.lims.eoms.modules.app.utils.vo.BasicQueueBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.connector.CoyoteAdapter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@Service("repairOrderService")
public class RepairOrderServiceImpl extends ServiceImpl<RepairOrderDao, RepairOrderEntity> implements RepairOrderService {

    @Autowired
    private PlanScopeService planScopeService ;
    @Autowired
    private PicService picService ;
    @Autowired
    private RepairOrderRecordService repairOrderRecordService ;
    @Autowired
    private QueueSendMessageService queueSendMessageService ;

    @Override
    public PageUtils queryPage(RepairOrderListReq req,Long userId) {
        QueryWrapper<RepairOrderEntity> queryWrapper = new QueryWrapper<>() ;
        if(req.getStatus()!=null) {
            queryWrapper.eq("status",req.getStatus()) ;
        }
        if (StringUtils.isNotBlank(req.getCode())){
            queryWrapper.like("code","%"+req.getCode()+"%") ;
        }
        if (!CollectionUtils.isEmpty(req.getCreateByList())){
            queryWrapper.in("create_by",req.getCreateByList()) ;
        }
        if (!CollectionUtils.isEmpty(req.getAgentIdList())){
            queryWrapper.in("agent_id",req.getAgentIdList()) ;
        }
        if (req.getIsResolved()!=null){
            queryWrapper.eq("is_resolved",req.getIsResolved()) ;
        }
        if (StringUtils.isNotBlank(req.getName())){
            queryWrapper.like("name","%"+req.getName()+"%") ;
        }
        queryWrapper.eq("is_del",0) ;

        queryWrapper.orderByDesc(" create_time") ;
        IPage<RepairOrderEntity> page = this.page(
                new Query<RepairOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(RepairOrderReq req,Long userId) {
        //1、添加维修记录
        RepairOrderEntity orderEntity = new RepairOrderEntity() ;
        BeanUtils.copyProperties(req,orderEntity);
        orderEntity.setCode(CodeUtils.getCode(Constants.REPAIR_CODE_BEGIN_WITH,Constants.CODE_LEN));
        orderEntity.setCreateBy(userId);
        orderEntity.setCreateTime(new Date());
        orderEntity.setIsDel(0);
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.save(orderEntity) ;
        //2、添加问题设备
        if (!CollectionUtils.isEmpty(req.getEquipmentIdList())){
            List<PlanScopeEntity> planScopeEntityList = new ArrayList<>() ;
            req.getEquipmentIdList().forEach(e->{
                PlanScopeEntity planScopeEntity = new PlanScopeEntity() ;
                planScopeEntity.setPlanId(orderEntity.getId());
                planScopeEntity.setScopeId(e);
                planScopeEntity.setType(BusiTypeEnum.REPAIRORDER.getCode());
                planScopeEntity.setIsDel(0);
                planScopeEntityList.add(planScopeEntity) ;
            });
            planScopeService.saveBatch(planScopeEntityList) ;
        }
        //3、添加现场图片
        if (!CollectionUtils.isEmpty(req.getPicList())){
            List<PicEntity> picEntityList = new ArrayList<>() ;
            req.getPicList().forEach(e->{
                PicEntity picEntity = new PicEntity() ;
                picEntity.setBusiId(orderEntity.getId());
                picEntity.setType(BusiTypeEnum.REPAIRORDER.getCode());
                picEntity.setPic(e);
                picEntityList.add(picEntity) ;
            });
            picService.saveBatch(picEntityList) ;
        }
        //4、添加日志记录
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;
        orderRecordEntity.setRepairOrderId(orderEntity.getId());
        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setOperation("发起工单");
        orderRecordEntity.setExplain("经办人:"+req.getAgentId());
        repairOrderRecordService.save(orderRecordEntity) ;

        //TODO 5、推送提醒
        /**
         * "标题：维修工单提醒
         * 提醒内容：
         * 你有一个维修工单需要处理
         * 工单编号：XXXXX
         * 问题级别：XX
         * 问题设备：XXXXXX"
         */
        RepairOrderMsg msg = new RepairOrderMsg() ;
        msg.setTitle("维修工单提醒");
        msg.setContent("你有一个维修工单需要处理");
        msg.setReceiver(orderEntity.getAgentId()+"");
        msg.setLevelDes(RepairLeveEnum.getDesc(orderEntity.getLevel()));
        msg.setCode(orderEntity.getCode());
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),orderRecordEntity.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setEquipmentIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        queueSendMessageService.sendMessage(QueueUtils.REPAIR_ORDER_ADD,msg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderById(RepairOrderReq req,Long userId) {

        Long agentId = null ;
        //1、修改维修记录
        //1.1、判断是非未开始时
        RepairOrderEntity orderEntity =this.getById(req.getId()) ;

        if (Objects.isNull(orderEntity) || orderEntity.getId() ==null) {
            throw new RRException("记录不存在") ;
        }
        //1.2、未开始可以修改，否则不可修改
        if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("维修订单只有未开始状态可以修改") ;
        }
        agentId = orderEntity.getAgentId() ;

        //1.3、修改状态
        BeanUtils.copyProperties(req,orderEntity);
        orderEntity.setIsDel(0);
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //2、添加问题设备
        //2.1、删除原记录设备
        planScopeService.deleteByPlanId(BusiTypeEnum.REPAIRORDER.getCode(),req.getId()) ;
        //2.2、添加设备记录
        if (!CollectionUtils.isEmpty(req.getEquipmentIdList())){
            List<PlanScopeEntity> planScopeEntityList = new ArrayList<>() ;
            req.getEquipmentIdList().forEach(e->{
                PlanScopeEntity planScopeEntity = new PlanScopeEntity() ;
                planScopeEntity.setPlanId(orderEntity.getId());
                planScopeEntity.setScopeId(e);
                planScopeEntity.setType(BusiTypeEnum.REPAIRORDER.getCode());
                planScopeEntity.setIsDel(0);
                planScopeEntityList.add(planScopeEntity) ;
            });
            planScopeService.saveBatch(planScopeEntityList) ;
        }
        //3、添加现场图片
        //3.1、删除现场图片
        picService.deleteByTypeAndBusiId(BusiTypeEnum.REPAIRORDER.getCode(),req.getId()) ;
        //3.2、添加现场图片
        if (!CollectionUtils.isEmpty(req.getPicList())){
            List<PicEntity> picEntityList = new ArrayList<>() ;
            req.getPicList().forEach(e->{
                PicEntity picEntity = new PicEntity() ;
                picEntity.setBusiId(orderEntity.getId());
                picEntity.setType(BusiTypeEnum.REPAIRORDER.getCode());
                picEntity.setPic(e);
                picEntityList.add(picEntity) ;
            });
            picService.saveBatch(picEntityList) ;
        }
        //4、添加日志记录
        String operation = null ;
        String explain = null ;
        if (req.getAgentId().equals(agentId)) {
            operation = "修改维修工单" ;
            explain = "修改维修工单" ;
        }else{
            operation = "修改经办人" ;
            explain = "修改工单经办人："+req.getAgentId() ;
        }
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;
        orderRecordEntity.setRepairOrderId(orderEntity.getId());
        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setOperation(operation);
        orderRecordEntity.setExplain(explain);
        repairOrderRecordService.save(orderRecordEntity) ;

        //TODO 5、推送提醒
        /**
         * "标题：维修工单提醒
         * 提醒内容：
         * 你有一个维修工单需要处理
         * 工单编号：XXXXX
         * 问题级别：XX
         * 问题设备：XXXXXX"
         */
        if (!req.getAgentId().equals(agentId)) {
            RepairOrderMsg msg = new RepairOrderMsg() ;
            msg.setTitle("维修工单提醒");
            msg.setContent("你有一个维修工单需要处理");
            msg.setReceiver(orderEntity.getAgentId()+"");
            msg.setLevelDes(RepairLeveEnum.getDesc(orderEntity.getLevel()));
            msg.setCode(orderEntity.getCode());
            //查询保养范围
            List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),orderRecordEntity.getId()) ;
            if (!CollectionUtils.isEmpty(scopeList)){
                msg.setEquipmentIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
            }
            queueSendMessageService.sendMessage(QueueUtils.REPAIR_ORDER_ADD,msg);
        }
    }

    @Override
    public RepairOrderInfoRes queryOrderById(Long id,Long userId) {
        RepairOrderInfoRes res = new RepairOrderInfoRes() ;
        RepairOrderEntity orderEntity = this.getById(id) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        BeanUtils.copyProperties(orderEntity,res);
        //读取问题设备列表
        List<PlanScopeEntity> planScopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(planScopeList)){
            res.setEquipmentIdList(planScopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        //读取现场图片
        List<PicEntity> picEntityList = picService.listByTypeAndBusiId(BusiTypeEnum.REPAIRORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(picEntityList)) {
            res.setPicList(picEntityList.stream().map(PicEntity::getPic).collect(Collectors.toList()));
        }


        //读取维修日志
        res.setRecordList(analysisList(userId,orderEntity));
/*
        //读取维修日志
        List<RepairOrderRecordEntity> repairOrderEntityList = null ;
        if (userId.equals(orderEntity.getCreateBy())){
            //判断当前用户是否创建人，如果创建人可以看到所有日志信息
            repairOrderEntityList = repairOrderRecordService.listByOrderId(id) ;
        }else {
            //非创建人只能看到自己操作信息
            repairOrderEntityList = repairOrderRecordService.listByOperatorAndOrderId(userId,id) ;
        }

        if (repairOrderEntityList != null && !CollectionUtils.isEmpty(repairOrderEntityList)) {
            List<RepairOrderInfoRes.OrderRecordRes> recordResList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(repairOrderEntityList)) {
                repairOrderEntityList.stream().forEach(e -> {
                    RepairOrderInfoRes.OrderRecordRes recordRes = new RepairOrderInfoRes.OrderRecordRes();
                    BeanUtils.copyProperties(e, recordRes);
                    recordResList.add(recordRes);
                });
            }
            res.setRecordList(recordResList);
        }*/
        return res;
    }

    @Override
    public void accept(AcceptOrderReq req,Long userId) {
        //接受工单
        //1、判断当前状态
        RepairOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }
        /*if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("订单非未开始状态不能接受") ;
        }
        */

        orderEntity.setStatus(OrderStatusEnum.STARTED.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        //更新
        this.updateById(orderEntity) ;

        //添加日志记录
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setRepairOrderId(req.getId());
        orderRecordEntity.setOperation("接受工单");
        orderRecordEntity.setExplain("计划维修时间："+req.getPlanDate());
        repairOrderRecordService.save(orderRecordEntity) ;
    }

    @Override
    public void reject(RejectOrderReq req,Long userId) {
        //拒绝工单
        //1、判断当前状态
        RepairOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }
        /*if (!OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())){
            throw new RRException("订单非未开始状态不能拒绝") ;
        }*/
        orderEntity.setStatus(OrderStatusEnum.REJECT.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        //修改经办人，创建人/发起人变成经办人
        orderEntity.setAgentId(orderEntity.getCreateBy());
        //更新
        this.updateById(orderEntity) ;

        //添加日志记录
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setRepairOrderId(req.getId());
        orderRecordEntity.setOperation("拒绝工单");
        orderRecordEntity.setExplain("拒绝原因："+req.getReason());
        repairOrderRecordService.save(orderRecordEntity) ;

        //TODO 发送消息，通知发起人

        /**
         * "标题：维修工单提醒
         * 提醒内容：
         * 你有一个维修工单被拒绝，请及时处理
         * 工单编号：XXXXX
         * 问题级别：XX
         * 问题设备：XXXXXX
         * 拒绝原因：XXXXXXXX"
         */
        RejectOrderMsg msg = new RejectOrderMsg() ;
        msg.setTitle("维修工单提醒");
        msg.setContent("你有一个维修工单被拒绝，请及时处理");
        msg.setReceiver(orderEntity.getAgentId()+"");
        msg.setLevelDes(RepairLeveEnum.getDesc(orderEntity.getLevel()));
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),orderRecordEntity.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setEquipmentIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        queueSendMessageService.sendMessage(QueueUtils.REPAIR_ORDER_REJECT,msg);
    }

    @Override
    public void updateAgent(ModifyAgentOrderReq req,Long userId) {
        //修改经办人
        RepairOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getCreateBy())){
            throw new RRException("当前的登录人非发起人" );
        }
        //未开始、已完成、已拒绝状态，报修人可修改经办人
        if (!(OrderStatusEnum.NOT_STARTED.getCode().equals(orderEntity.getStatus())
                ||OrderStatusEnum.COMPLETE.getCode().equals(orderEntity.getStatus())
        ||OrderStatusEnum.REJECT.getCode().equals(orderEntity.getStatus()))){
            throw new RRException("未开始、已完成、已拒绝状态可修改经办人") ;
        }

        //修改
        orderEntity.setAgentId(req.getAgentId());
        orderEntity.setStatus(OrderStatusEnum.NOT_STARTED.getCode());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //添加记录
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setRepairOrderId(req.getId());
        orderRecordEntity.setOperation("修改经办人");
        orderRecordEntity.setExplain("修改工单经办人为："+req.getAgentId());
        repairOrderRecordService.save(orderRecordEntity) ;
        //TODO 发送消息，通知经办人
        RepairOrderMsg msg = new RepairOrderMsg() ;
        msg.setTitle("维修工单提醒");
        msg.setContent("你有一个维修工单需要处理");
        msg.setReceiver(orderEntity.getAgentId()+"");
        msg.setLevelDes(RepairLeveEnum.getDesc(orderEntity.getLevel()));
        msg.setCode(orderEntity.getCode());
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),orderRecordEntity.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setEquipmentIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        queueSendMessageService.sendMessage(QueueUtils.REPAIR_ORDER_ADD,msg);
    }

    @Override
    public void uploadResult(RepairUploadResultReq req,Long userId) {
        //修改订单状态
        RepairOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getAgentId())){
            throw new RRException("当前的登录人非经办人" );
        }

        orderEntity.setStatus(OrderStatusEnum.COMPLETE.getCode());
        orderEntity.setIsResolved(req.getIsResolved());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        //修改经办人
        orderEntity.setAgentId(orderEntity.getCreateBy());
        this.updateById(orderEntity) ;

        //添加日志
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setRepairOrderId(req.getId());
        orderRecordEntity.setOperation("上传维修结果");
        orderRecordEntity.setExplain("维修完成时间："+ LocalDateUtils.format(req.getCompleteTime(),LocalDateUtils.DATE_PATTERN)
                +";问题是否解决："+(req.getIsResolved()==0?"未解决":"已解决")
                +";维修方案："+req.getPlanContent());
        repairOrderRecordService.save(orderRecordEntity) ;

        //TODO 推送消息,给发起人推送消息
        CompleteRepairOrderMsg msg = new CompleteRepairOrderMsg() ;
        msg.setTitle("维修工单提醒");
        msg.setContent("你有一个维修工单需要处理");
        msg.setReceiver(orderEntity.getCreateBy()+"");
        msg.setLevelDes(RepairLeveEnum.getDesc(orderEntity.getLevel()));
        msg.setCode(orderEntity.getCode());
        //查询保养范围
        List<PlanScopeEntity> scopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),orderRecordEntity.getId()) ;
        if (!CollectionUtils.isEmpty(scopeList)){
            msg.setEquipmentIdList(scopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        msg.setRepairTime(LocalDateUtils.format(req.getCompleteTime(),LocalDateUtils.DATE_TIME_MINUTE_PATTERN));
        msg.setResult(req.getIsResolved()==1?"已解决":"未解决");
        queueSendMessageService.sendMessage(QueueUtils.REPAIR_ORDER_COMPLETE,msg);
    }

    @Override
    public void closeOrder(RepairCloseReq req,Long userId) {

        //修改订单状态
        RepairOrderEntity orderEntity = this.getById(req.getId()) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }
        if(!userId.equals(orderEntity.getCreateBy())){
            throw new RRException("当前的登录人非发起人" );
        }
        orderEntity.setStatus(OrderStatusEnum.CLOSE.getCode());
        orderEntity.setIsResolved(req.getIsResolved());
        orderEntity.setUpdateBy(userId);
        orderEntity.setUpdateTime(new Date());
        this.updateById(orderEntity) ;

        //添加日志
        RepairOrderRecordEntity orderRecordEntity = new RepairOrderRecordEntity() ;

        orderRecordEntity.setOperatorId(userId);
        orderRecordEntity.setOperatorTime(new Date());
        orderRecordEntity.setRepairOrderId(req.getId());
        orderRecordEntity.setOperation("工单关闭");
        orderRecordEntity.setExplain("问题是否解决："+(req.getIsResolved()==0?"未解决":"已解决")
                +";维修总结："+req.getSummary());
        repairOrderRecordService.save(orderRecordEntity) ;
    }

    @Override
    public PageUtils queryAppPage(AppUserRepairListReq req,Long userId) {

        QueryWrapper<RepairOrderEntity> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("create_by",userId) ;
        queryWrapper.eq("is_del",0) ;
        if (req.getOrderType()==2){
            //已处理
            queryWrapper.eq("status",OrderStatusEnum.CLOSE.getCode()) ;
            queryWrapper.ge("update_time",LocalDateUtils.addDateDays(new Date(),-7)) ;
            queryWrapper.orderByDesc("update_time") ;
        }else{
            //待处理
            queryWrapper.ne("status",OrderStatusEnum.CLOSE.getCode()) ;
            queryWrapper.orderByDesc("create_time") ;
        }
        IPage<RepairOrderEntity> page = this.page(
                new Query<RepairOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                queryWrapper
        );

        IPage<AppRepairListRes> retPage = new Page<>(page.getCurrent(),page.getSize()) ;
        retPage.setPages(page.getPages()) ;
        retPage.setTotal(page.getTotal()) ;

        List<AppRepairListRes> resList = new ArrayList<>() ;
        //处理业务
        if (!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().stream().forEach(e->{
                AppRepairListRes res = new AppRepairListRes() ;
                BeanUtils.copyProperties(e,res);
                resList.add(res) ;
            });
        }
        retPage.setRecords(resList) ;
        return new PageUtils(retPage);

    }

    @Override
    public PageUtils queryWxPage(AppUserRepairListReq req,Long userId) {
        QueryWrapper<RepairOrderEntity> queryWrapper = new QueryWrapper<>() ;

        queryWrapper.eq("is_del",0) ;
        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(OrderStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(OrderStatusEnum.STARTED.getCode()) ;
        //已处理
        if (req.getOrderType()==2){
            //查询登录人参与维修的项目
            List<RepairOrderRecordEntity> repairList = repairOrderRecordService.listByOperatorId(userId) ;
            List<Long> repairIdList = new ArrayList<>( ) ;
            if (CollectionUtils.isEmpty(repairList)){
                repairIdList.add(null) ;
            }else{
                repairIdList = repairList.stream().map(RepairOrderRecordEntity::getRepairOrderId).collect(Collectors.toList());
            }
            //已处理列表，历史经办人为本人的全部工单
            queryWrapper.in("id",repairIdList) ;
            //当前经办人不只是自己
            //queryWrapper.ne("agent_id",userId) ;
            queryWrapper.and(wrapper->wrapper.or(p->p.in("status",statusList).ne("agent_id",userId)).or(pp->pp.notIn("status",statusList))) ;
            queryWrapper.orderByDesc("update_time") ;

        }else{
            //待处理列表,本人待处理工单，未开始，处理中的订单，最后一次分配倒序，及update_time 倒序
            queryWrapper.eq("agent_id",userId) ;
            queryWrapper.in("status",statusList) ;
            queryWrapper.orderByDesc("create_time") ;
        }

        IPage<RepairOrderEntity> page = this.page(
                new Query<RepairOrderEntity>().getPage(ObjectToMapUtils.setConditionMap(req)),
                queryWrapper
        );

        IPage<AppRepairListRes> retPage = new Page<>(page.getCurrent(),page.getSize()) ;
        retPage.setPages(page.getPages()) ;
        retPage.setTotal(page.getTotal()) ;

        List<AppRepairListRes> resList = new ArrayList<>() ;
        //处理业务
        if (!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().stream().forEach(e->{
                AppRepairListRes res = new AppRepairListRes() ;
                BeanUtils.copyProperties(e,res);
                resList.add(res) ;
            });
        }

        retPage.setRecords(resList) ;
        return new PageUtils(retPage);
    }

    @Override
    public RepairOrderInfoRes queryWxOrderById(Long id,Long userId) {

        RepairOrderInfoRes res = new RepairOrderInfoRes() ;
        RepairOrderEntity orderEntity = this.getById(id) ;
        if (Objects.isNull(orderEntity)||orderEntity.getId()==null){
            throw new RRException("记录不存在") ;
        }

        BeanUtil.copyProperties(orderEntity,res,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        //读取问题设备列表
        List<PlanScopeEntity> planScopeList= planScopeService.listByTypeAndPlanId(BusiTypeEnum.REPAIRORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(planScopeList)){
            res.setEquipmentIdList(planScopeList.stream().map(PlanScopeEntity::getScopeId).collect(Collectors.toList()));
        }
        //读取现场图片
        List<PicEntity> picEntityList = picService.listByTypeAndBusiId(BusiTypeEnum.REPAIRORDER.getCode(),id) ;
        if (!CollectionUtils.isEmpty(picEntityList)) {
            res.setPicList(picEntityList.stream().map(PicEntity::getPic).collect(Collectors.toList()));
        }

        //读取维修日志
        res.setRecordList(analysisList(userId,orderEntity));
        return res;
    }

    private List<RepairOrderInfoRes.OrderRecordRes> analysisList(Long userId,RepairOrderEntity orderEntity){
        //读取维修日志
        List<RepairOrderRecordEntity> repairOrderEntityList =  repairOrderRecordService.listByOrderId(orderEntity.getId()) ;
        List<RepairOrderInfoRes.OrderRecordRes> recordResList = new ArrayList<>();
        if (userId.equals(orderEntity.getCreateBy())){
            //判断当前用户是否创建人，如果创建人可以看到所有日志信息
            if (!CollectionUtils.isEmpty(repairOrderEntityList)) {
                repairOrderEntityList.stream().forEach(e -> {
                    RepairOrderInfoRes.OrderRecordRes recordRes = new RepairOrderInfoRes.OrderRecordRes();
                    BeanUtil.copyProperties(e, recordRes,true,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                    recordRes.setUserId(StringConstants.analysisExplain(recordRes.getOperation(),recordRes.getExplain()));
                    recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),recordRes.getUserId()));
                    recordResList.add(recordRes);
                });
            }
        }else {
            //非创建人只能看到自己操作信息
            if (!CollectionUtils.isEmpty(repairOrderEntityList)) {
                repairOrderEntityList.stream().forEach(e -> {
                    if("关闭工单".equals(e.getOperation())){// 关闭当前人的工单)
                        //如果为关闭工单，需要查看上一条记录是否当事人，是的情况隐藏维修总结,否则不可见
                        if (!CollectionUtils.isEmpty(recordResList)){
                            RepairOrderInfoRes.OrderRecordRes tempRecord = recordResList.get(recordResList.size()-1) ;
                            if (userId.equals(tempRecord.getOperatorId())){//上一条操作记录是当前登录人
                                RepairOrderInfoRes.OrderRecordRes recordRes = new RepairOrderInfoRes.OrderRecordRes();
                                BeanUtil.copyProperties(e, recordRes,true,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)) ;
                                if(recordRes.getExplain() != null && recordRes.getExplain().contains(";维修总结：")){
                                    recordRes.setExplain(recordRes.getExplain().substring(0,recordRes.getExplain().indexOf(";维修总结：")));
                                }
                                recordRes.setUserId(StringConstants.analysisExplain(recordRes.getOperation(),recordRes.getExplain()));
                                recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),recordRes.getUserId()));
                                recordResList.add(recordRes) ;
                            }
                        }
                    }else{
                        Long tempUserId = StringConstants.analysisExplain(e.getOperation(),e.getExplain()) ;
                        if (tempUserId.equals(userId) //指向给当前人
                                || e.getOperatorId().equals(userId) //当前人操作
                        ){
                            RepairOrderInfoRes.OrderRecordRes recordRes = new RepairOrderInfoRes.OrderRecordRes();
                            BeanUtil.copyProperties(e, recordRes,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)) ;
                            recordRes.setUserId(tempUserId);
                            recordRes.setExplain(StringConstants.analysisExplain(recordRes.getExplain(),tempUserId));
                            recordResList.add(recordRes);
                        }
                    } 
                });
            }
        }
        Collections.reverse(recordResList);
        return recordResList ;
    }

}